﻿using Fetches.Fetch.Dto;
using Fetches.Fetch.Utils;

namespace Fetches.Fetch.Scheduler.Component
{
    /// <summary>
    /// BloomFilterDuplicateRemover for huge number of urls.
    /// </summary>
    public class BloomFilterDuplicateRemover : IDuplicateRemover
    {
        private BloomFilter _bloomFilter;
        private readonly BloomFilterOptions _options;


        /// <summary>
        /// 构造方法
        /// </summary>
        public BloomFilterDuplicateRemover(BloomFilterOptions options)
        {
            _options = options;
            _bloomFilter = new BloomFilter(_options.FalsePositiveProbability, _options.ExpectedInsertions);
        }

        /// <summary>
        /// Check whether the request is duplicate.
        /// </summary>
        /// <param name="request">Request</param>
        /// <returns>Whether the request is duplicate.</returns>
        public bool IsDuplicate(Request request)
        {
            var hash = request.Hash;
            var isDuplicate = _bloomFilter.Contains(hash);
            if (!isDuplicate)
            {
                _bloomFilter.Add(hash);
            }

            return isDuplicate;
        }

        /// <summary>
        /// Reset duplicate check.
        /// </summary>
        public void ResetDuplicateCheck()
        {
            _bloomFilter.Clear();
            _bloomFilter = new BloomFilter(_options.FalsePositiveProbability, _options.ExpectedInsertions);
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public void Dispose()
        {
            _bloomFilter.Clear();
        }
    }
}
